{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "58b94329",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Matplotlib is building the font cache; this may take a moment.\n"
     ]
    }
   ],
   "source": [
    "# 导入需要的包\n",
    "import numpy as np\n",
    "import torch\n",
    "from torch.utils import data\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98c804bb",
   "metadata": {},
   "source": [
    "## 线性回归公式\n",
    "\n",
    "y = w₁x₁ + w₂x₂ + ... + wₙxₙ + b​\n",
    "\n",
    "其中：\n",
    "\n",
    "- ​w₁, w₂, ..., wₙ​ 是权重（weights），表示每个特征对输出的影响程度。\n",
    "- ​x₁, x₂, ..., xₙ​ 是输入特征（features）。\n",
    "- ​b​ 是偏置（bias），表示当所有特征为0时的基准输出值。\n",
    "- ​y​ 是预测的目标值（label）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "15ec5a97",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[-1.0025, -0.3906],\n",
      "        [-0.3450, -1.4680],\n",
      "        [ 0.2527,  0.4503],\n",
      "        [ 0.6993, -0.9264],\n",
      "        [ 0.4835, -1.7913]]) \n",
      " tensor([[ 3.5020],\n",
      "        [ 8.4845],\n",
      "        [ 3.1504],\n",
      "        [ 8.7439],\n",
      "        [11.2584]])\n"
     ]
    }
   ],
   "source": [
    "# 定义两个特征权重w1, w2\n",
    "true_w = torch.tensor([2, -3.4])\n",
    "# 定义偏置b\n",
    "true_b = 4.2\n",
    "features, labels = d2l.synthetic_data(true_w, true_b, 1000)\n",
    "\n",
    "print(features[:5], \"\\n\", labels[:5])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "815455c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_array(data_arrays, batch_size, is_train=True):\n",
    "    \"\"\"构造一个PyTorch数据迭代器\"\"\"\n",
    "    dataset = data.TensorDataset(*data_arrays)\n",
    "    return data.DataLoader(dataset, batch_size, shuffle=is_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ab35d181",
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size = 10\n",
    "data_iter = load_array((features, labels), batch_size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "be2d5ada",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[tensor([[ 1.7299, -1.2156],\n",
       "         [-0.1612, -0.1318],\n",
       "         [-0.8134, -2.5241],\n",
       "         [ 0.1248,  0.0547],\n",
       "         [ 0.6729, -0.1107],\n",
       "         [-0.2769, -0.9490],\n",
       "         [ 1.1435,  0.7602],\n",
       "         [ 0.0758, -0.8914],\n",
       "         [-0.7289,  1.2373],\n",
       "         [ 1.0365,  1.2363]]),\n",
       " tensor([[11.7933],\n",
       "         [ 4.3164],\n",
       "         [11.1489],\n",
       "         [ 4.2495],\n",
       "         [ 5.9173],\n",
       "         [ 6.8885],\n",
       "         [ 3.9100],\n",
       "         [ 7.3691],\n",
       "         [-1.4490],\n",
       "         [ 2.0601]])]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "next(iter(data_iter))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3f6a4532",
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch import nn\n",
    "\n",
    "net = nn.Sequential(nn.Linear(2,1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0e3b475b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0.])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net[0].weight.data.normal_(0, 0.01)\n",
    "net[0].bias.data.fill_(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "318e03e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义损失函数\n",
    "loss = nn.MSELoss()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f59f77a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义优化算法\n",
    "trainer = torch.optim.SGD(net.parameters(), lr=0.03)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "4b88616d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.000100\n",
      "epoch 2, loss 0.000100\n",
      "epoch 3, loss 0.000100\n"
     ]
    }
   ],
   "source": [
    "# 训练\n",
    "num_epochs = 3\n",
    "for epoch in range(num_epochs):\n",
    "    for X, y in data_iter:\n",
    "        # 前向传播\n",
    "        l = loss(net(X), y.view(-1, 1))\n",
    "        # 清零梯度\n",
    "        trainer.zero_grad()\n",
    "        # 反向传播\n",
    "        l.backward()\n",
    "        # 更新参数\n",
    "        trainer.step()\n",
    "    l = loss(net(features), labels.view(-1, 1))\n",
    "    print(f'epoch {epoch + 1}, loss {l:f}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "b26d8d68",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "w的估计误差: tensor([-2.1696e-05,  1.0583e-03])\n",
      "b的估计误差: tensor([1.6689e-05])\n"
     ]
    }
   ],
   "source": [
    "w = net[0].weight.data\n",
    "print(\"w的估计误差:\", true_w - w.reshape(true_w.shape))\n",
    "b = net[0].bias.data\n",
    "print(\"b的估计误差:\", true_b - b)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "deep-learning-pytorch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.22"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
